from django.contrib import admin
from .models import Task, Job, JobOutput
from django.conf.urls import url
from django.http import HttpResponseRedirect
from django.core.urlresolvers import NoReverseMatch, reverse


class TaskAdmin(admin.ModelAdmin):
    fields = ('do', 'name', 'module', 'name_template', 'dependence', 'raw_conf', 'max_retry', 'live')
    readonly_fields = ('do', )
    list_display = ('name', 'live')

    def get_urls(self):
        urls = super(TaskAdmin, self).get_urls()
        urls = [url(r'^(.+)/create_job/$', self.admin_site.admin_view(self.create_job), name="{}_{}_create_job".format(self.model._meta.app_label, self.model._meta.model_name))] + urls
        import logging
        logger = logging.getLogger('django')
        logger.error(urls)
        return urls
    
    def do(self, obj):
        create_job_url = reverse("admin:{}_{}_create_job".format(obj._meta.app_label, obj._meta.model_name), args=(obj.id,))
        return '<a class="button" href="{}">create_job</a>'.format(create_job_url)
    do.allow_tags = True

    def create_job(self, request, id):
        job = Task.objects.get(pk=id).create_job()
        task_url = reverse("admin:{}_{}_change".format(job._meta.app_label, job._meta.model_name), args=(job.pk,))
        return HttpResponseRedirect(task_url)


class JobOutputInline(admin.StackedInline):
    model = JobOutput
    readonly_fields = ['key']
    fields = ['key', 'value']

    def has_add_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return False


class JobAdmin(admin.ModelAdmin):
    readonly_fields = ('dependence', 'name', 'task_link', 'log', 'status', 'retry', 'begin', 'end', 'do')
    fields = ('do', 'name', 'task_link',  'status', 'dependence', 'retry', ('begin', 'end'), 'log')
    list_display = ('task', 'name', 'date', 'status', 'begin', 'end', 'delta_time')
    search_fields = ('name', )
    list_filter = ('date', )
    inlines = [ JobOutputInline ]

    def delta_time(self, obj):
        if obj.begin and obj.end:
            return obj.end - obj.begin
        return ''

    def get_urls(self):
        urls = super(JobAdmin, self).get_urls()
        urls = [url(r'^(.+)/run/$', self.admin_site.admin_view(self.run), name="{}_{}_run".format(self.model._meta.app_label, self.model._meta.model_name))] + urls
        urls = [url(r'^(.+)/restart/$', self.admin_site.admin_view(self.restart), name="{}_{}_restart".format(self.model._meta.app_label, self.model._meta.model_name))] + urls
        return urls

    def do(self, obj):
        if obj.status in (Job.Status.pending, Job.Status.waiting):
            run_url = reverse("admin:{}_{}_run".format(obj._meta.app_label, obj._meta.model_name), args=(obj.id,))
            return '<a class="button" href="{}">run</a>'.format(run_url)
        elif obj.status == Job.Status.running:
            return ''
        else:
            restart_url = reverse("admin:{}_{}_restart".format(obj._meta.app_label, obj._meta.model_name), args=(obj.id, ))
            return '<a class="button" href="{}">restart</a>'.format(restart_url)
    do.allow_tags = True

    def task_link(self, obj):
        task_url = reverse("admin:{}_{}_change".format(obj.task._meta.app_label, obj.task._meta.model_name), args=(obj.task.id,))
        return '<a href="{}">{}</a>'.format(task_url, unicode(obj.task))
    task_link.allow_tags = True

    def run(self, request, id):
        job = Job.objects.get(pk=id)
        job.start()
        change_url = reverse("admin:{}_{}_change".format(job._meta.app_label, job._meta.model_name), args=(job.pk,))
        return HttpResponseRedirect(change_url)

    def restart(self, request, id):
        job = Job.objects.get(pk=id)
        job.restart()
        change_url = reverse("admin:{}_{}_change".format(job._meta.app_label, job._meta.model_name), args=(job.pk,))
        return HttpResponseRedirect(change_url)
        
    def has_add_permission(self, request, obj=None):
        return False

class JobOutputAdmin(admin.ModelAdmin):
    readonly_fields = JobOutput._meta.get_fields()
    list_display = ['key', 'job_name']
    def job_name(self, obj, *args, **kwargs):
        job = Job.objects.get(outputs=obj)
        return unicode(job)


# Register your models here.
admin.site.register(Task, TaskAdmin)
admin.site.register(Job, JobAdmin)
